import axios from 'axios'
import InfoUtils from '../utils/InfoUtil.js'
import {useRouter} from 'vue-router'

const router = useRouter();
//请求前置处理忽略地址
const requestProcessingIgnorePaths = ['/user/createLoginCode'];
//响应后置处理忽略地址
const responseProcessingIgnorePaths = ['/user/createLoginCode'];
let baseURL = "http://localhost:8877"

const axiosRequest = axios.create({
    baseURL
});


//统一前置处理
axiosRequest.interceptors.request.use(function (config) {

    for (let i = 0; i < requestProcessingIgnorePaths.length; i++) {
        if (requestProcessingIgnorePaths[i] == config.url) {
            return config;
        }
    }
    //如果存在token 则携带上
    let token = localStorage.getItem("token");
    if (token != undefined || token != '') {
        config.headers['token'] = token;
    }
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

//统一后置处理
axiosRequest.interceptors.response.use(function (response) {
    let responseData = response.data;
    for (let i = 0; i < responseProcessingIgnorePaths.length; i++) {
        if (responseProcessingIgnorePaths[i] == response.config.url) {
            return responseData;
        }
    }
    //过期的情况
    if (responseData.code == 401 || responseData.code == 403) {
        localStorage.removeItem("token");
        router.push("/login")
    }

    return responseData;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});


export default {
    //发送post请求
    async sendPostRequest(requestPath, requestData) {
        let response;
        await axiosRequest.post(requestPath, requestData).then((res) => {
            response = res;
        });
        return response;
    },

    //发送get请求
    async sendGetRequest(requestPath, requestData) {
        let response;
        await axiosRequest.get(requestPath, {params: {...requestData}}).then((res) => {
            response = res;
        });
        return response;
    },

    //发送获取图片请求
    async sendGetRequestGetImage(requestPath, requestData) {
        const result = await axiosRequest.get(requestPath, {
            params: {...requestData},
            responseType: 'blob'
        });

        if (result.type == 'application/json') {
            const reader = new FileReader();  //创建一个FileReader实例
            reader.readAsText(result, 'utf-8'); //读取文件,结果用字符串形式表示
            reader.onload = function () {//读取完成后,**获取reader.result**
                let response = JSON.parse(reader.result);
                InfoUtils.warning(response.message)
            }
            return null;
        }
        return window.URL.createObjectURL(new Blob([result], {type: 'application/png'}));
    },

    //发送post请求上传文件
    async sendPostRequestUploadImg(requestPath, requestData) {
        let param = new FormData()
        let result;
        for (let key in requestData) {
            param.append(key, requestData[key][0]);
        }
        await axiosRequest.post(requestPath, param, {
            'Content-type': 'multipart/form-data'
        }).then(response => {
            result = response;
        });
        return result;
    },
    getRequestUrl(path) {

        console.log(axiosRequest);
        return baseURL + path;
    }


}

